using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//↓「PixelFormat.Format32bppPArgb」を使用するので追加
using System.Drawing.Imaging;
namespace test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//四角形の位置とサイズを格納するオブジェクト
Rectangle rc;
//サイズを格納するオブジェクト
Size sz;
//サイズ設定
sz = new Size(50, 50);
//ディスプレイの範囲を取得
rc = Screen.PrimaryScreen.Bounds;
//画像格納様ビットマップ作成
//Bitmap bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppPArgb);
Bitmap bmp = new Bitmap(50, 50, PixelFormat.Format32bppPArgb);
//描画サーフェイス「using」を使い、自動でGraphicsのDisposeを行っている
using (Graphics g = Graphics.FromImage(bmp))
{
//画面から色データのビットブロック転送
//ここではディスプレイの右上からの画像を
//コピー先の座標(0,0)へ
//サイズ、色を変更せずコピー
g.CopyFromScreen(0, 0, 0, 0,sz, CopyPixelOperation.SourceCopy);
}
//ピクチャボックスへ画像貼り付け
pictureBox1.Image = bmp;
}
private void button2_Click(object sender, EventArgs e)
{
//変数の宣言
int i, j, iAverage;
Bitmap bBitmap;
Color cColor;
//ピクチャボックスの画像取得
bBitmap = new Bitmap(pictureBox1.Image);
//画像の2値化の実行
for (i = 0; i < pictureBox1.Image.Width; i++)
{
//画像の幅分繰り返し
for (j = 0; j < pictureBox1.Image.Height; j++)
{
//画像の高さ分繰り返し
//1ピクセル分の色取得
cColor = bBitmap.GetPixel(i, j);
//色の平均値取得
iAverage = GetColorAve(cColor);
//閾値との比較
if (iAverage <= int.Parse(textBox1.Text))
{
//RGB平均値が閾値以下の場合
//白色に設定する
bBitmap.SetPixel(i, j, Color.White);
}
else
{
// RGB平均値が閾値より大きい場合
//黒色に設定する
bBitmap.SetPixel(i, j, Color.Black);
}
}
}
//結果を表示
pictureBox1.Image = bBitmap;
}
private int GetColorAve(Color cColor)
{
//変数宣言
int iBlue;
int iRed;
int iGreen;
int iAverage;
//Blue値の設定
iBlue = cColor.B;
//Green値の設定
iGreen = cColor.G;
//Red値の設定
iRed = cColor.R;
//平均値計算
iAverage = (iBlue + iGreen + iRed) / 3;
//平均値の返却
return iAverage;
}
}
}